package myapp.camera;

import java.util.ArrayList;

import myapp.DTO.CategoryDTO;
import myapp.DTO.ServiceDTO;
import myapp.EnumAndConstans.Constants;
import myapp.database.CategoryDB;
import myapp.googlemap.GoogleMapActivity;
import myapp.googlemap.R;
import myapp.helper.OrientationHelper;
import myapp.services.DbServiceHelper;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class AddNewServiceActivity extends Activity {

	int category_position = 0;
	ArrayList<CategoryDTO> lcategoryDTO;
	double latitude;
	double longitude;
	static private EditText editText_service_name;
	static private Spinner spinner_category;
	static private EditText editText_service_address;
	static private EditText editText_service_phone;
	static private EditText editText_service_description;
	private Button button_set_location;
	private Button button_ok;
	private Button button_cancel;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_new_service);	

		Log.i("AddNewService", "onCreate");	
		
		latitude = OrientationHelper.getCurLat();
		longitude = OrientationHelper.getCurLon();

		
		/*
		 * Load save instance state
		 */
		editText_service_name = (EditText) findViewById(R.id.editText_name_add_new_service);
		editText_service_address = (EditText) findViewById(R.id.editText_address_add_new_service);
		editText_service_phone = (EditText) findViewById(R.id.editText_phone_add_new_service);
		editText_service_description = (EditText) findViewById(R.id.editText_description_add_new_service);	
		
		
		String service_name = null;
		String service_address = null;
		String service_phone = null;
		String service_description = null;
		if(savedInstanceState!=null)
	    {
			service_name = savedInstanceState.getString("editText_service_name");
			service_address= savedInstanceState.getString("editText_service_address");
			service_phone = savedInstanceState.getString("editText_service_phone");
			service_description= savedInstanceState.getString("editText_service_description");
			category_position = savedInstanceState.getInt("category_position");
	    }

	    if(service_name != null)
	    	editText_service_name.setText(service_name);
	    if(service_address != null)
	    	editText_service_address.setText(service_address);
	    if(service_name != null)
	    	editText_service_phone.setText(service_phone);
	    if(service_address != null)
	    	editText_service_description.setText(service_description);
	    
	    
	    
		/*
		 * Spinner: select category
		 */
		spinner_category = (Spinner) findViewById(R.id.spinner_category_add_new_service);
		spinner_category.setSelection(category_position);
		ArrayList<String> categories = new ArrayList<String>();
		CategoryDB caDB = new CategoryDB(this);
		caDB.open();
		lcategoryDTO = caDB.getAllCategories();
		caDB.close();
		for (CategoryDTO c : lcategoryDTO)
			categories.add(c.getName());
		
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, categories);
		spinner_category.setAdapter(dataAdapter);
		
		spinner_category.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				category_position = arg2;
				Log.i("Add_newService", lcategoryDTO.get(category_position).getName());
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}			
		});
		
		
		/*
		 * Set service's location
		 * Default: service's location is device's location
		 */
		button_set_location = (Button) findViewById(R.id.button_set_location_add_new_service);
		button_set_location.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(AddNewServiceActivity.this, GoogleMapActivity.class);				
				myIntent.putExtra("state_of_googlemap", Constants.STATE_GOOGLEMAP_SET_SERVICE_LOCATION);
				startActivityForResult(myIntent, Constants.ADD_NEW_SERVICE_ACTIVITY_REQUESTCODE);				
			}
		});
		
		
		/*
		 * Button OK
		 */
		button_ok = (Button) findViewById(R.id.button_OK_add_new_service);
		button_ok.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder dialog_status = new AlertDialog.Builder(AddNewServiceActivity.this);
		    	final AlertDialog.Builder adialog = new AlertDialog.Builder(AddNewServiceActivity.this);
		    	adialog.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
				        AddNewServiceActivity.this.setResult(RESULT_OK);
				        finish();
					}
				});
		    	
		    	dialog_status.setIcon(R.drawable.icon_attention);
		    	dialog_status.setTitle("Confirm Action");
		    	dialog_status.setMessage("Do you want add service on server?");
		    	//dialog_status.setOnCancelListener(onCancelListener)
		    	new AlertDialog.Builder(AddNewServiceActivity.this)
				.setIcon(R.drawable.icon_attention)
				.setTitle("Confirm Action")
				.setMessage("Do you want add service on server?")
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
				    	DbServiceHelper dbsh = new DbServiceHelper();
				    	try					
					    {	
					    	ServiceDTO service = new ServiceDTO(editText_service_name.getText().toString(),
					    			lcategoryDTO.get(category_position).getId(),
					    			latitude,
					    			longitude,
					    			editText_service_address.getText().toString(), 
					    			editText_service_phone.getText().toString(),
					    			editText_service_description.getText().toString());
					    	
					    	dbsh.AddNewService(service);
					    	
				    		adialog.setTitle("Succes");
				    		adialog.setMessage(editText_service_name.getText().toString()+"\n"+
				    				editText_service_address.getText().toString()+"\n"+
				    				editText_service_phone.getText().toString()+"\n"+
				    				editText_service_description.getText().toString()+"\n"+
				    				String.valueOf(latitude)+"\n"+
				    				String.valueOf(longitude)+"\n"+
				    				String.valueOf(lcategoryDTO.get(category_position).getId())
				    				);
				    		adialog.show();
				    	}
				    	catch (Exception exc)
				    	{
				    		adialog.setTitle("Failure");
				    		adialog.setMessage("Can not add new service");
				    		adialog.show();
				    	}
					};
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				})
				.show();
				

			}
		});

		
		/*
		 * Button Cancel
		 */
		button_cancel = (Button) findViewById(R.id.button_Cancel_add_new_service);
		button_cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		        AddNewServiceActivity.this.setResult(RESULT_CANCELED);
		        finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.add_new, menu);
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("AddNewService", "onActivityResult");
		switch (requestCode) {
		case (Constants.ADD_NEW_SERVICE_ACTIVITY_REQUESTCODE):
			if (resultCode == RESULT_OK)
			{
				latitude = data.getDoubleExtra("latitude_service", OrientationHelper.getCurLat());
				longitude = data.getDoubleExtra("longitude_service", OrientationHelper.getCurLat());						
			}
			break;

		default:
			break;
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putString("editText_service_name", editText_service_name.getText().toString());
        outState.putString("editText_service_address", editText_service_address.getText().toString());
        outState.putString("editText_service_phone", editText_service_phone.getText().toString());
        outState.putString("editText_service_description", editText_service_description.getText().toString());
        outState.putInt("category_position", category_position);
	}

}
